import pathlib
import time
import re
import typing
import os
import rich.traceback
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
import enum
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *

# 导入 rich 组件
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.table import Table
from rich.columns import Columns
from rich.align import Align
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn
from rich.prompt import Prompt
from rich.markdown import Markdown
from rich.syntax import Syntax
from rich.tree import Tree
from rich.layout import Layout
from rich.live import Live

# 初始化rich跟踪回溯和控制台
rich.traceback.install()
console = Console()

# ------------------------------
# 样式配置
# ------------------------------
class Styles:
    """样式配置类"""
    SUCCESS = "bold green"
    ERROR = "bold red"
    WARNING = "bold yellow"
    INFO = "bold blue"
    HIGHLIGHT = "bold cyan"
    STEP = "bold magenta"
    CONDITION = "bold white"
    ELEMENT = "bold bright_white"
    SECTION = "bold bright_white"

# ------------------------------
# 条件类型枚举定义
# ------------------------------
class ConditionType(enum.Enum):
    """元素验证条件的枚举类型"""
    # 输入框值验证
    InputValueIsNull = 1          # 输入框值为空
    InputValueIsNotNull = 2       # 输入框值不为空
    InputValueEqual = 3           # 输入框值等于指定值
    InputValueNotEqual = 4        # 输入框值不等于指定值
    InputValueInclude = 5         # 输入框值包含指定内容
    InputValueNotInclude = 6      # 输入框值不包含指定内容
    
    # 文本内容验证
    TextValueIsNull = 7           # 文本内容为空
    TextValueIsNotNull = 8        # 文本内容不为空
    TextValueEqual = 9            # 文本内容等于指定值
    TextValueNotEqual = 10        # 文本内容不等于指定值
    TextValueInclude = 11         # 文本内容包含指定内容
    TextValueNotInclude = 12      # 文本内容不包含指定内容
    
    # 元素状态验证
    ElementIsEnabled = 13         # 元素可用
    ElementIsDisabled = 14        # 元素不可用
    ElementIsVisible = 15         # 元素可见
    ElementIsInvisible = 16       # 元素不可见
    ElementIsSelected = 17        # 元素被选中
    ElementIsNotSelected = 18     # 元素未被选中

# ------------------------------
# 输出美化工具类
# ------------------------------
class OutputDecorator:
    """输出美化装饰器"""
    
    @staticmethod
    def print_section_header(title: str, icon: str = "📋", style: str = Styles.SECTION):
        """打印章节头部"""
        console.print()
        console.rule(f"{icon} {title}", style=style)
        console.print()
    
    @staticmethod
    def print_condition_info(condition_type: str, xpath: str, expected_value: str = None, condition_name: str = "条件"):
        """打印条件信息"""
        table = Table(show_header=False, box=None, padding=(0, 2), show_lines=True)
        table.add_column("属性", style=Styles.CONDITION, width=15)
        table.add_column("值", style=Styles.INFO)
        
        table.add_row("条件类型", f"[{Styles.HIGHLIGHT}]{condition_type}[/{Styles.HIGHLIGHT}]")
        table.add_row("XPath", f"[{Styles.ELEMENT}]{xpath}[/{Styles.ELEMENT}]")
        if expected_value:
            table.add_row("预期值", f"[{Styles.HIGHLIGHT}]{expected_value}[/{Styles.HIGHLIGHT}]")
        else:
            table.add_row("预期值", "无")
        
        panel = Panel(
            table,
            title=f"🔍 {condition_name}信息",
            border_style="cyan",
            padding=(1, 2)
        )
        console.print(panel)
        console.print()
    
    @staticmethod
    def print_success(message: str, icon: str = "✅"):
        """打印成功消息"""
        console.print(f"{icon} [{Styles.SUCCESS}]{message}[/{Styles.SUCCESS}]")
    
    @staticmethod
    def print_error(message: str, icon: str = "❌"):
        """打印错误消息"""
        console.print(f"{icon} [{Styles.ERROR}]{message}[/{Styles.ERROR}]")
    
    @staticmethod
    def print_warning(message: str, icon: str = "⚠️"):
        """打印警告消息"""
        console.print(f"{icon} [{Styles.WARNING}]{message}[/{Styles.WARNING}]")
    
    @staticmethod
    def print_info(message: str, icon: str = "ℹ️"):
        """打印信息消息"""
        console.print(f"{icon} [{Styles.INFO}]{message}[/{Styles.INFO}]")
    
    @staticmethod
    def print_separator():
        """打印分隔线"""
        console.print("─" * 80, style="dim")

# ------------------------------
# 条件验证器类
# ------------------------------
class ConditionVerifier:
    """条件验证器，负责前置条件和后置条件的验证逻辑"""
    
    @staticmethod
    def verify_condition(
        driver: WebDriver,
        xpath: str,
        condition_type: typing.Optional[ConditionType] = None,
        expected_value: typing.Optional[str] = None,
        timeout: int = 10,
        loop_interval: float = 0.1
    ) -> bool:
        """
        验证指定元素是否满足条件
        
        Args:
            driver: WebDriver实例
            xpath: 要验证的元素XPath
            condition_type: 验证条件类型
            expected_value: 预期值（部分条件需要）
            timeout: 验证超时时间
            loop_interval: 验证间隔时间
            
        Returns:
            条件是否满足
        """
        if not xpath:  # 空XPath视为条件自动满足
            return True
            
        condition_name = condition_type.name if condition_type else "无条件"
        
        # 显示条件验证信息
        OutputDecorator.print_condition_info(condition_name, xpath, expected_value, "验证条件")
        
        start_time = datetime.datetime.now()
        
        # 使用更简洁的进度显示
        with console.status(f"[bold blue]验证条件中...[/bold blue]", spinner="dots"):
            while start_time + datetime.timedelta(seconds=timeout) > datetime.datetime.now():
                try:
                    element = driver.find_element(by=By.XPATH, value=xpath)
                    
                    # 根据条件类型进行验证
                    if not condition_type:
                        OutputDecorator.print_success("条件验证通过（无条件）")
                        return True
                        
                    # 输入框值验证
                    elif condition_type == ConditionType.InputValueIsNull:
                        result = element.get_attribute("value") == ""
                    elif condition_type == ConditionType.InputValueIsNotNull:
                        result = element.get_attribute("value") != ""
                    elif condition_type == ConditionType.InputValueEqual:
                        result = element.get_attribute("value") == expected_value
                    elif condition_type == ConditionType.InputValueNotEqual:
                        result = element.get_attribute("value") != expected_value
                    elif condition_type == ConditionType.InputValueInclude:
                        result = expected_value in element.get_attribute("value") if expected_value else False
                    elif condition_type == ConditionType.InputValueNotInclude:
                        result = expected_value not in element.get_attribute("value") if expected_value else True
                        
                    # 文本内容验证
                    elif condition_type == ConditionType.TextValueIsNull:
                        result = element.text == ""
                    elif condition_type == ConditionType.TextValueIsNotNull:
                        result = element.text != ""
                    elif condition_type == ConditionType.TextValueEqual:
                        result = element.text == expected_value
                    elif condition_type == ConditionType.TextValueNotEqual:
                        result = element.text != expected_value
                    elif condition_type == ConditionType.TextValueInclude:
                        result = expected_value in element.text if expected_value else False
                    elif condition_type == ConditionType.TextValueNotInclude:
                        result = expected_value not in element.text if expected_value else True
                    
                    # 元素状态验证
                    elif condition_type == ConditionType.ElementIsEnabled:
                        result = element.is_enabled()
                    elif condition_type == ConditionType.ElementIsDisabled:
                        result = not element.is_enabled()
                    elif condition_type == ConditionType.ElementIsVisible:
                        result = element.is_displayed()
                    elif condition_type == ConditionType.ElementIsInvisible:
                        result = not element.is_displayed()
                    elif condition_type == ConditionType.ElementIsSelected:
                        result = element.is_selected()
                    elif condition_type == ConditionType.ElementIsNotSelected:
                        result = not element.is_selected()
                    
                    if result:
                        OutputDecorator.print_success(f"条件验证通过: {condition_name}")
                        return True
                        
                except NoSuchElementException:
                    pass  # 元素未找到，继续等待
                except Exception as e:
                    OutputDecorator.print_error(f"条件验证发生错误: {str(e)}")
                    
                time.sleep(loop_interval)
            
            # 超时处理
            OutputDecorator.print_error(f"条件验证超时: {condition_name}")
            return False

# ------------------------------
# 元素查找器类（简化版，只负责查找元素）
# ------------------------------
class ElementFinder:
    """元素查找器，只负责查找元素，不涉及后置条件"""
    
    @staticmethod
    def find_element(
        driver: WebDriver,
        target_xpath: str,
        step_name: str = "未命名步骤",
        # 前置条件参数（可选）
        precondition_xpath: str = None,
        precondition_type: ConditionType = None,
        precondition_value: str = None,
        # 查找配置
        timeout: int = 10,
        retry_count: int = 0,
        loop_interval: float = 0.1,
        terminate_on_failure: bool = False
    ) -> typing.Optional[WebElement]:
        """
        查找元素（可选的预处理条件）
        
        Args:
            driver: WebDriver实例
            target_xpath: 目标元素XPath
            step_name: 步骤名称
            precondition_xpath: 前置条件元素XPath
            precondition_type: 前置条件类型
            precondition_value: 前置条件预期值
            timeout: 超时时间
            retry_count: 重试次数
            loop_interval: 循环间隔
            terminate_on_failure: 失败时是否终止
            
        Returns:
            找到的元素或None
        """
        max_attempts = retry_count + 1
        attempt = 0
        
        while attempt < max_attempts:
            attempt += 1
            
            # 步骤头部
            OutputDecorator.print_section_header(f"查找元素: {step_name} (尝试 {attempt}/{max_attempts})", "🔍", Styles.STEP)
            
            # ==================== 1. 前置条件验证（可选） ====================
            if precondition_xpath:
                OutputDecorator.print_section_header("前置条件验证", "📋", "yellow")
                
                precondition_name = precondition_type.name if precondition_type else "无条件"
                pre_conditions_met = ConditionVerifier.verify_condition(
                    driver=driver,
                    xpath=precondition_xpath,
                    condition_type=precondition_type,
                    expected_value=precondition_value,
                    timeout=timeout,
                    loop_interval=loop_interval
                )
                
                if not pre_conditions_met:
                    if terminate_on_failure:
                        console.print()
                        console.print(Panel.fit(
                            "🚨 前置条件未满足，程序终止！",
                            title="终止执行", border_style="red"
                        ))
                        exit(0)
                    OutputDecorator.print_warning("前置条件未满足，将重试...")
                    continue
                    
                OutputDecorator.print_success("前置条件验证通过")
                OutputDecorator.print_separator()
                console.print()
            
            # ==================== 2. 目标元素查找 ====================
            OutputDecorator.print_section_header("执行元素查找", "🎯", "blue")
            
            # 显示目标元素信息
            target_table = Table(show_header=False, box=None, padding=(0, 2), show_lines=True)
            target_table.add_column("属性", style=Styles.CONDITION, width=15)
            target_table.add_column("值", style=Styles.INFO)
            target_table.add_row("目标XPath", f"[{Styles.ELEMENT}]{target_xpath}[/{Styles.ELEMENT}]")
            target_table.add_row("超时时间", f"{timeout}秒")
            
            console.print(Panel(
                target_table,
                title="🔍 查找配置",
                border_style="blue",
                padding=(1, 2)
            ))
            console.print()
            
            target_element = None
            start_time = datetime.datetime.now()
            
            # 查找元素
            with console.status(f"[bold blue]查找目标元素中...[/bold blue]", spinner="dots"):
                while start_time + datetime.timedelta(seconds=timeout) > datetime.datetime.now():
                    try:
                        target_element = driver.find_element(By.XPATH, target_xpath)
                        break
                    except NoSuchElementException:
                        time.sleep(loop_interval)
                        continue
            
            if not target_element:
                OutputDecorator.print_error("未找到目标元素，将重试...")
                continue
                
            OutputDecorator.print_success("目标元素找到")
            
            # ==================== 3. 查找成功 ====================
            console.print()
            success_panel = Panel.fit(
                f"✅ [bold green]元素查找成功！[/bold green]\n\n"
                f"📝 [bold]步骤名称:[/bold] {step_name}\n"
                f"🔢 [bold]尝试次数:[/bold] {attempt}/{max_attempts}\n"
                f"🎯 [bold]目标元素:[/bold] {target_xpath}",
                title="🎉 查找完成",
                border_style="green",
                padding=(1, 4)
            )
            console.print(success_panel)
            console.print()
            
            return target_element

        # ==================== 4. 所有尝试都失败 ====================
        console.print()
        error_panel = Panel.fit(
            f"❌ [bold red]元素查找失败！[/bold red]\n\n"
            f"📝 [bold]步骤名称:[/bold] {step_name}\n"
            f"🔢 [bold]最大尝试:[/bold] {max_attempts}次\n"
            f"🎯 [bold]目标元素:[/bold] {target_xpath}",
            title="💥 查找失败",
            border_style="red",
            padding=(1, 4)
        )
        console.print(error_panel)
        console.print()
        
        return None

# ------------------------------
# 鼠标操作工具类（重构版，包含前置和后置条件）
# ------------------------------
class MouseOperator:
    """鼠标操作工具类，提供带条件验证的鼠标操作"""
    
    @staticmethod
    def click_element(
        driver: WebDriver,
        target_xpath: str,
        step_name: str = "未命名点击操作",
        # 操作前条件参数
        pre_condition_xpath: str = None,
        pre_condition_type: ConditionType = None,
        pre_condition_value: str = None,
        # 操作后条件参数
        post_condition_xpath: str = None,
        post_condition_type: ConditionType = None,
        post_condition_value: str = None,
        # 元素状态条件（点击前验证元素本身状态）
        element_condition_type: ConditionType = ConditionType.ElementIsEnabled,
        # 通用参数
        timeout: int = 10,
        retry_count: int = 0,
        loop_interval: float = 0.1,
        terminate_on_failure: bool = False
    ) -> bool:
        """
        带条件验证的元素点击操作
        
        Args:
            driver: WebDriver实例
            target_xpath: 目标元素XPath
            step_name: 步骤名称
            pre_condition_xpath: 点击前验证元素XPath
            pre_condition_type: 点击前验证条件类型
            pre_condition_value: 点击前验证预期值
            post_condition_xpath: 点击后验证元素XPath
            post_condition_type: 点击后验证条件类型
            post_condition_value: 点击后验证预期值
            element_condition_type: 元素自身状态验证条件
            其他参数: 超时、重试等配置
            
        Returns:
            操作是否成功
        """
        OutputDecorator.print_section_header(f"鼠标点击操作: {step_name}", "🖱️", Styles.STEP)
        
        # ==================== 1. 前置条件验证 ====================
        if pre_condition_xpath:
            OutputDecorator.print_section_header("执行前条件验证", "📋", "yellow")
            
            pre_conditions_met = ConditionVerifier.verify_condition(
                driver=driver,
                xpath=pre_condition_xpath,
                condition_type=pre_condition_type,
                expected_value=pre_condition_value,
                timeout=timeout,
                loop_interval=loop_interval
            )
            
            if not pre_conditions_met:
                if terminate_on_failure:
                    console.print()
                    console.print(Panel.fit(
                        "🚨 前置条件未满足，程序终止！",
                        title="终止执行", border_style="red"
                    ))
                    exit(0)
                OutputDecorator.print_error("前置条件未满足，操作终止")
                return False
                
            OutputDecorator.print_success("前置条件验证通过")
            OutputDecorator.print_separator()
            console.print()
        
        # ==================== 2. 查找目标元素 ====================
        OutputDecorator.print_section_header("查找目标元素", "🔍", "blue")
        
        target_element = ElementFinder.find_element(
            driver=driver,
            target_xpath=target_xpath,
            step_name=f"{step_name} - 查找点击目标",
            timeout=timeout,
            retry_count=retry_count,
            loop_interval=loop_interval,
            terminate_on_failure=terminate_on_failure
        )
        
        if not target_element:
            OutputDecorator.print_error(f"{step_name} - 未找到可点击的目标元素")
            return False
        
        # ==================== 3. 验证元素状态 ====================
        OutputDecorator.print_section_header("验证元素状态", "📊", "yellow")
        
        element_ready = False
        
        # 针对元素自身状态进行验证
        if element_condition_type == ConditionType.ElementIsEnabled:
            element_ready = target_element.is_enabled()
        elif element_condition_type == ConditionType.ElementIsVisible:
            element_ready = target_element.is_displayed()
        else:
            element_ready = ConditionVerifier.verify_condition(
                driver=driver,
                xpath=target_xpath,
                condition_type=element_condition_type,
                timeout=timeout,
                loop_interval=loop_interval
            )
        
        if not element_ready:
            OutputDecorator.print_error(f"{step_name} - 元素状态不满足点击条件")
            if terminate_on_failure:
                exit(0)
            return False
        
        OutputDecorator.print_success("元素状态检查通过")
        OutputDecorator.print_separator()
        console.print()
        
        # ==================== 4. 执行点击操作 ====================
        OutputDecorator.print_section_header("执行点击操作", "🚀", "blue")
        
        try:
            # 尝试滚动到元素可见位置
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", target_element)
            time.sleep(loop_interval)
            
            # 优先尝试正常点击
            target_element.click()
            OutputDecorator.print_success("点击操作执行完成")
            
        except ElementClickInterceptedException:
            # 处理点击被拦截的情况
            OutputDecorator.print_warning("正常点击被拦截，尝试JavaScript点击")
            driver.execute_script("arguments[0].click();", target_element)
            OutputDecorator.print_success("JavaScript点击执行完成")
        except Exception as e:
            OutputDecorator.print_error(f"点击操作发生错误: {str(e)}")
            return False
        
        # ==================== 5. 后置条件验证 ====================
        if post_condition_xpath:
            OutputDecorator.print_section_header("执行后条件验证", "📋", "cyan")
            
            post_conditions_met = ConditionVerifier.verify_condition(
                driver=driver,
                xpath=post_condition_xpath,
                condition_type=post_condition_type,
                expected_value=post_condition_value,
                timeout=timeout,
                loop_interval=loop_interval
            )
            
            if not post_conditions_met:
                OutputDecorator.print_error("后置条件未满足")
                if terminate_on_failure:
                    exit(0)
                return False
            
            OutputDecorator.print_success("后置条件验证通过")
        
        # ==================== 6. 操作成功完成 ====================
        console.print()
        success_panel = Panel.fit(
            f"✅ [bold green]点击操作成功完成！[/bold green]\n\n"
            f"📝 [bold]步骤名称:[/bold] {step_name}\n"
            f"🎯 [bold]目标元素:[/bold] {target_xpath}\n"
            f"🖱️ [bold]操作类型:[/bold] 鼠标点击",
            title="🎉 操作成功",
            border_style="green",
            padding=(1, 4)
        )
        console.print(success_panel)
        console.print()
        
        return True

# ------------------------------
# 键盘操作工具类（重构版，包含前置和后置条件）
# ------------------------------
class KeyboardOperator:
    """键盘操作工具类，提供带条件验证的键盘输入操作"""
    
    @staticmethod
    def input_text(
        driver: WebDriver,
        target_xpath: str,
        input_text: str,
        step_name: str = "未命名输入操作",
        # 操作前条件参数
        pre_condition_xpath: str = None,
        pre_condition_type: ConditionType = None,
        pre_condition_value: str = None,
        # 操作后条件参数
        post_condition_xpath: str = None,
        post_condition_type: ConditionType = None,
        post_condition_value: str = None,
        # 输入框状态条件
        element_condition_type: ConditionType = ConditionType.ElementIsEnabled,
        # 输入选项
        clear_before_input: bool = True,  # 输入前是否清空
        press_enter_after: bool = False,  # 输入后是否按回车
        # 通用参数
        timeout: int = 10,
        retry_count: int = 0,
        loop_interval: float = 0.1,
        terminate_on_failure: bool = False
    ) -> bool:
        """
        带条件验证的文本输入操作
        
        Args:
            driver: WebDriver实例
            target_xpath: 目标输入框XPath
            input_text: 要输入的文本
            step_name: 步骤名称
            pre_condition_xpath: 输入前验证元素XPath
            pre_condition_type: 输入前验证条件类型
            pre_condition_value: 输入前验证预期值
            post_condition_xpath: 输入后验证元素XPath
            post_condition_type: 输入后验证条件类型
            post_condition_value: 输入后验证预期值
            element_condition_type: 输入框状态验证条件
            clear_before_input: 输入前是否清空
            press_enter_after: 输入后是否按回车
            其他参数: 超时、重试等配置
            
        Returns:
            操作是否成功
        """
        OutputDecorator.print_section_header(f"键盘输入操作: {step_name}", "⌨️", Styles.STEP)
        
        # ==================== 1. 前置条件验证 ====================
        if pre_condition_xpath:
            OutputDecorator.print_section_header("执行前条件验证", "📋", "yellow")
            
            pre_conditions_met = ConditionVerifier.verify_condition(
                driver=driver,
                xpath=pre_condition_xpath,
                condition_type=pre_condition_type,
                expected_value=pre_condition_value,
                timeout=timeout,
                loop_interval=loop_interval
            )
            
            if not pre_conditions_met:
                if terminate_on_failure:
                    console.print()
                    console.print(Panel.fit(
                        "🚨 前置条件未满足，程序终止！",
                        title="终止执行", border_style="red"
                    ))
                    exit(0)
                OutputDecorator.print_error("前置条件未满足，操作终止")
                return False
                
            OutputDecorator.print_success("前置条件验证通过")
            OutputDecorator.print_separator()
            console.print()
        
        # ==================== 2. 查找目标元素 ====================
        OutputDecorator.print_section_header("查找输入框元素", "🔍", "blue")
        
        target_element = ElementFinder.find_element(
            driver=driver,
            target_xpath=target_xpath,
            step_name=f"{step_name} - 查找输入框",
            timeout=timeout,
            retry_count=retry_count,
            loop_interval=loop_interval,
            terminate_on_failure=terminate_on_failure
        )
        
        if not target_element:
            OutputDecorator.print_error(f"{step_name} - 未找到目标输入框元素")
            return False
        
        # ==================== 3. 验证输入框状态 ====================
        OutputDecorator.print_section_header("验证输入框状态", "📊", "yellow")
        
        element_ready = False
        
        if element_condition_type == ConditionType.ElementIsEnabled:
            element_ready = target_element.is_enabled()
        elif element_condition_type == ConditionType.ElementIsVisible:
            element_ready = target_element.is_displayed()
        else:
            element_ready = ConditionVerifier.verify_condition(
                driver=driver,
                xpath=target_xpath,
                condition_type=element_condition_type,
                timeout=timeout,
                loop_interval=loop_interval
            )
        
        if not element_ready:
            OutputDecorator.print_error(f"{step_name} - 输入框状态不满足输入条件")
            if terminate_on_failure:
                exit(0)
            return False
        
        OutputDecorator.print_success("输入框状态检查通过")
        OutputDecorator.print_separator()
        console.print()
        
        # ==================== 4. 执行输入操作 ====================
        OutputDecorator.print_section_header("执行输入操作", "🚀", "blue")
        
        # 显示输入信息
        input_table = Table(show_header=False, box=None, padding=(0, 2), show_lines=True)
        input_table.add_column("属性", style=Styles.CONDITION, width=15)
        input_table.add_column("值", style=Styles.INFO)
        input_table.add_row("输入内容", f"[{Styles.HIGHLIGHT}]{input_text}[/{Styles.HIGHLIGHT}]")
        input_table.add_row("输入前清空", "✅" if clear_before_input else "❌")
        input_table.add_row("输入后回车", "✅" if press_enter_after else "❌")
        
        console.print(Panel(
            input_table,
            title="📝 输入操作信息",
            border_style="blue",
            padding=(1, 2)
        ))
        console.print()
        
        try:
            # 滚动到元素可见位置
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", target_element)
            time.sleep(loop_interval)
            
            # 点击输入框获取焦点
            target_element.click()
            time.sleep(loop_interval)
            
            # 输入前清空
            if clear_before_input:
                target_element.clear()
                target_element.send_keys(Keys.CONTROL + "a")
                target_element.send_keys(Keys.DELETE)
            
            # 输入文本
            target_element.send_keys(input_text)
            time.sleep(loop_interval)
            
            # 输入后按回车
            if press_enter_after:
                target_element.send_keys(Keys.ENTER)
                OutputDecorator.print_info("已按下回车键")
            
            OutputDecorator.print_success("输入操作执行完成")
            
        except Exception as e:
            OutputDecorator.print_error(f"输入操作发生错误: {str(e)}")
            return False
        
        # ==================== 5. 后置条件验证 ====================
        if post_condition_xpath:
            OutputDecorator.print_section_header("执行后条件验证", "📋", "cyan")
            
            post_conditions_met = ConditionVerifier.verify_condition(
                driver=driver,
                xpath=post_condition_xpath,
                condition_type=post_condition_type,
                expected_value=post_condition_value,
                timeout=timeout,
                loop_interval=loop_interval
            )
            
            if not post_conditions_met:
                OutputDecorator.print_error("后置条件未满足")
                if terminate_on_failure:
                    exit(0)
                return False
            
            OutputDecorator.print_success("后置条件验证通过")
        
        # ==================== 6. 操作成功完成 ====================
        console.print()
        success_panel = Panel.fit(
            f"✅ [bold green]输入操作成功完成！[/bold green]\n\n"
            f"📝 [bold]步骤名称:[/bold] {step_name}\n"
            f"📝 [bold]输入内容:[/bold] {input_text}\n"
            f"🎯 [bold]目标元素:[/bold] {target_xpath}",
            title="🎉 输入成功",
            border_style="green",
            padding=(1, 4)
        )
        console.print(success_panel)
        console.print()
        
        return True

# ------------------------------
# 浏览器控制工具类（保持不变）
# ------------------------------
class BrowserController:
    """浏览器控制工具类，负责浏览器进程管理和驱动初始化"""
    
    @staticmethod
    def show_message(parent_hwnd: int = 0, title: str = '提示', text: str = '默认文本', msg_type: int = 0) -> int:
        """显示自定义消息框"""
        return ctypes.windll.user32.MessageBoxW(parent_hwnd, text, title, msg_type)
    
    @staticmethod
    def is_process_running(process_name: str = "msedge.exe") -> bool:
        """检查是否存在指定名称的进程"""
        for proc in psutil.process_iter(['name']):
            if proc.info['name'] == process_name:
                return True
        return False
    
    @staticmethod
    def is_debug_mode_active(local: str = "127.0.0.1", port: str = "9652") -> bool:
        """检查调试模式是否激活"""
        url = f"http://{local}:{port}/json/version"
        try:
            response = requests.get(url=url, timeout=5)
            return response.status_code == 200
        except Exception as e:
            OutputDecorator.print_error(f"调试模式检查错误: {e}")
            return False
    
    @staticmethod
    def close_all_processes(process_name: str = "msedge.exe") -> bool:
        """关闭所有指定名称的进程"""
        success = True
        processes_closed = 0
        
        OutputDecorator.print_section_header("进程管理", "🔄", "yellow")
        
        for proc in psutil.process_iter(['pid', 'name']):
            if process_name == proc.info['name']:
                try:
                    proc.kill()
                    processes_closed += 1
                    OutputDecorator.print_success(f"已关闭进程 PID: {proc.info['pid']}")
                except Exception as e:
                    OutputDecorator.print_error(f"关闭进程 PID: {proc.info['pid']} 失败: {e}")
                    success = False
        
        console.print()
        result_panel = Panel.fit(
            f"📊 [bold]进程关闭统计[/bold]\n\n"
            f"✅ [bold]成功关闭:[/bold] {processes_closed} 个进程\n"
            f"🎯 [bold]操作结果:[/bold] {'成功' if success else '部分失败'}",
            border_style="green" if success else "red",
            padding=(1, 2)
        )
        console.print(result_panel)
        console.print()
        
        return success
    
    @staticmethod
    def start_debug_mode_browser(
        local: str = "127.0.0.1",
        debug_port: int = 9652,
        user_data_dir: str = None,
        with_extensions: bool = False
    ):
        """启动带调试模式的浏览器"""
        OutputDecorator.print_section_header("浏览器启动", "🌐", "blue")
        
        # 构建启动命令
        if user_data_dir:
            command = rf'"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" --remote-debugging-port={debug_port} --user-data-dir="{user_data_dir}" "http://{local}:{debug_port}/json/version"'
        else:
            command = rf'"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" --remote-debugging-port={debug_port} "http://{local}:{debug_port}/json/version"'
        
        # 显示启动信息
        info_table = Table(show_header=False, box=None, padding=(0, 2), show_lines=True)
        info_table.add_column("属性", style=Styles.CONDITION, width=15)
        info_table.add_column("值", style=Styles.INFO)
        info_table.add_row("调试端口", f"{debug_port}")
        info_table.add_row("用户数据目录", f"{user_data_dir or '默认'}")
        
        console.print(Panel(
            info_table,
            title="🚀 启动配置",
            border_style="blue",
            padding=(1, 2)
        ))
        console.print()
        
        # 启动新进程
        CREATE_NEW_CONSOLE = 0x00000010
        subprocess.Popen(command, shell=True, creationflags=CREATE_NEW_CONSOLE)
        OutputDecorator.print_success(f"已启动调试模式浏览器，端口: {debug_port}")
        
        # 等待浏览器启动
        with console.status("[bold blue]等待浏览器启动...[/bold blue]", spinner="dots"):
            time.sleep(3)
    
    @staticmethod
    def create_driver_instance(
        local: str = "127.0.0.1", 
        port: int = 9652
    ) -> typing.Tuple[WebDriver, WebDriverWait, ActionChains]:
        """创建WebDriver、WebDriverWait和ActionChains实例"""
        OutputDecorator.print_section_header("驱动初始化", "⚙️", "cyan")
        
        options = Options()
        options.add_experimental_option("debuggerAddress", f"{local}:{port}")
        service = Service()
        driver = WebDriver(options=options, service=service)
        wait = WebDriverWait(driver=driver, timeout=10)
        actions = ActionChains(driver=driver)
        
        OutputDecorator.print_success("WebDriver实例创建成功")
        return driver, wait, actions
    
    @staticmethod
    def connect_debug_browser(
        local: str = "127.0.0.1",
        debug_port: int = 9652,
        user_data_dir: str = None
    ) -> typing.Tuple[WebDriver, WebDriverWait, ActionChains]:
        """连接到调试模式浏览器，如未启动则自动启动"""
        OutputDecorator.print_section_header("浏览器连接流程", "🌐", "bold blue")
        
        # 检查进程是否存在
        if not BrowserController.is_process_running():
            OutputDecorator.print_info("未检测到浏览器进程，启动新浏览器")
            BrowserController.start_debug_mode_browser(
                local=local, 
                debug_port=debug_port, 
                user_data_dir=user_data_dir
            )
        else:
            # 检查调试模式是否激活
            if not BrowserController.is_debug_mode_active(local=local, port=str(debug_port)):
                if user_data_dir is not None:
                    BrowserController.start_debug_mode_browser(
                        local=local, 
                        debug_port=debug_port, 
                        user_data_dir=user_data_dir
                    )
                else:
                    # 询问用户是否关闭现有进程
                    result = BrowserController.show_message(
                        title="提示",
                        text="检测到浏览器进程但未启用调试模式，是否关闭所有浏览器进程?",
                        msg_type=4  # YES/NO 按钮
                    )
                    if result == 6:  # YES
                        BrowserController.close_all_processes()
                        BrowserController.start_debug_mode_browser(
                            local=local, 
                            debug_port=debug_port
                        )
                    else:  # NO
                        console.print()
                        console.print(Panel.fit(
                            "👤 用户取消操作，程序退出",
                            title="❌ 操作取消", border_style="red"
                        ))
                        exit(0)
        
        # 连接到调试浏览器
        return BrowserController.create_driver_instance(local=local, port=debug_port)
    
    @staticmethod
    def switch_to_active_tab(driver: WebDriver, local: str = "127.0.0.1", port: int = 9652) -> None:
        """切换到当前激活的标签页"""
        try:
            debug_data = requests.get(f"http://{local}:{port}/json", timeout=5).json()
            if not isinstance(debug_data, list):
                OutputDecorator.print_error("调试接口返回数据格式不正确")
                return
                
            # 筛选有效的页面
            valid_pages = [
                page for page in debug_data 
                if page.get('type') == "page" and 
                not page.get('url', '').lower().startswith(("chrome-devtools", "chrome-extension"))
            ]
            
            if valid_pages:
                active_tab_id = valid_pages[0]['id']
                driver.switch_to.window(active_tab_id)
                OutputDecorator.print_success("已切换到激活标签页")
        except Exception as e:
            OutputDecorator.print_error(f"切换标签页失败: {e}")

# ------------------------------
# 使用示例
# ------------------------------
if __name__ == "__main__":
    try:
        # 程序开始
        console.print()
        console.rule("🚀 自动化脚本启动", style="bold green")
        console.print()
        
        # 连接到调试模式浏览器
        driver, wait, actions = BrowserController.connect_debug_browser(
            local="127.0.0.1",
            debug_port=9652
        )
        
        # 切换到激活标签页
        BrowserController.switch_to_active_tab(driver, port=9652)
        
        # 示例1: 简单的元素查找
        element = ElementFinder.find_element(
            driver=driver,
            target_xpath="//input[contains(@placeholder,'请输入')]",
            step_name="查找输入框",
            precondition_xpath="//input[contains(@placeholder,'请输入')]",
            precondition_type=ConditionType.InputValueIsNotNull,
            timeout=10
        )
        
        if element:
            # 示例2: 带条件的输入操作
            KeyboardOperator.input_text(
                driver=driver,
                target_xpath="//input[contains(@placeholder,'请输入')]",
                input_text="女装T恤",
                step_name="输入商品标题",
                # 前置条件：确保输入框为空
                pre_condition_xpath="//input[contains(@placeholder,'请输入')]",
                pre_condition_type=ConditionType.InputValueIsNotNull,
                # 后置条件：验证输入内容
                post_condition_xpath="//input[contains(@placeholder,'请输入')]",
                post_condition_type=ConditionType.InputValueEqual,
                post_condition_value="女装T恤",
                clear_before_input=True,
                press_enter_after=False,
                timeout=10,
                retry_count=1,
                terminate_on_failure=True
            )
        
    except Exception as e:
        console.print()
        console.print(Panel.fit(
            f"💥 执行出错: {str(e)}",
            title="❌ 错误信息", border_style="red"
        ))
    finally:
        console.print()
        console.rule("✅ 自动化操作完成", style="bold green")
        console.print()